package com.b2.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class AccessTokenUtils {
    public static String getAccessTokenOne(String appId,String appSecret) {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + appSecret;

        System.out.println("request user info from url: {" + url + "}");
        JsonObject accessTokenInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            //LOGGER.error("获取Token-------------------"+response);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);

            return accessTokenInfo.get("access_token").toString().replaceAll("\"", "");

        } catch (Exception ex) {
            System.out.println("fail to request wechat user info. [error={" + ex + "}]");
        }
        return "";
    }
}
